package com.xunsiya.controller;

import com.xunsiya.bean.ResultData;
import com.xunsiya.common.config.util.ConstantInfo;
import com.xunsiya.module.media.vo.Image;
import com.xunsiya.module.order.vo.OrderDetail;
import com.xunsiya.module.persons.vo.PersonsVo;
import com.xunsiya.service.module.device.DeviceService;
import com.xunsiya.service.module.media.MediaService;
import com.xunsiya.service.module.order.OrderService;
import com.xunsiya.service.module.persons.PersonsService;
import com.xunsiya.tools.common.config.PathUtils;
import com.xunsiya.tools.common.msg.Msg;
import com.xunsiya.tools.common.random.RandomUtil;
import com.xunsiya.tools.common.string.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * 识别管理Controller
 *
 * @author panjun
 * @version 1.0
 *          <p>
 *          <p>修订人		修订时间			描述信息
 *          <p>-----------------------------------------------------
 *          <p>panjun		2018/11/7		初始创建
 */
@RestController
public class RecognizeController {

    private final Logger log = Logger.getLogger(RecognizeController.class);
    /**
     * 人脸识别
     */
    public final static int PERSON_CAPACITY = 1;
    /**
     * 图像识别
     */
    public final static int MEDIA_CAPACITY = 2;
    @Autowired
    private PersonsService personsService;

    @Autowired
    private MediaService mediaService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DeviceService deviceSerive;

    @Value("${recog.path}")
    private String recogPath;

    private final static String DOT = ".";

    /**
     * 人脸识别
     *
     * @param deviceId 设备蓝牙地址
     * @param file 文件流
     * @return
     */
    @PostMapping("face/query/{deviceId}")
    public ResultData recogFace(@PathVariable String deviceId, MultipartFile file) {
        ResultData msg = new ResultData(false);
        if (file == null) {
            return new ResultData(false, ConstantInfo.HttpCode.HTTP_400.getDesc(), ConstantInfo.HttpCode.HTTP_400.getValue());
        }

        try {
            // 保存文件
            String path = saveFile(file);
            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }

            Integer companyId = deviceSerive.getDeviceId(deviceId);
            if (companyId == null) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }
            OrderDetail orderDetail = orderService.findByCompanyIdAndParentId(companyId,PERSON_CAPACITY);
            if(orderDetail == null)
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_600.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_600.getDesc());
                return msg;
            }
            //过期
            if(orderDetail.getOutDate().getTime() < (new Date()).getTime())
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_601.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_601.getDesc());
                return msg;
            }
            // 识别文件
            List<PersonsVo> personsVoList = personsService.recogFace(deviceId, path);
            // 返回值
            msg.setSuccess(true);
            if (personsVoList != null) {
                msg.setData(personsVoList);
            }
            msg.setCode(ConstantInfo.HttpCode.HTTP_200.getValue());
            msg.setMsg(ConstantInfo.HttpCode.HTTP_200.getDesc());
            return msg;
        } catch (IOException e) {
            log.error("文件保存失败");
        }

        msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
        msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
        return msg;
    }

    /**
     * 人脸识别
     *
     * @param deviceId 设备蓝牙地址
     * @param file 文件base64码
     * @return
     */
    @PostMapping("face/queryByBase64/{deviceId}")
    public ResultData recogFace(@PathVariable String deviceId, String file) {
        ResultData msg = new ResultData(false);
        if (StringUtil.isEmpty(file)) {
            return new ResultData(false, ConstantInfo.HttpCode.HTTP_400.getDesc(), ConstantInfo.HttpCode.HTTP_400.getValue());
        }

        // 保存文件
        String path = saveFileByBase64(file);
        if (StringUtil.isEmpty(path)) {
            msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
            msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
            return msg;
        }

        // 识别文件
        List<PersonsVo> personsVoList = personsService.recogFace(deviceId, path);

        // 返回值
        msg.setSuccess(true);
        if (personsVoList != null) {
            msg.setData(personsVoList);
        }
        msg.setCode(ConstantInfo.HttpCode.HTTP_200.getValue());
        msg.setMsg(ConstantInfo.HttpCode.HTTP_200.getDesc());
        return msg;

    }
    /**
     * 指纹搜索/图像识别
     * @param deviceId
     * @param file
     * @return
     */
    @PostMapping("/image/query/{deviceId}")
    public Msg search(@PathVariable String deviceId, MultipartFile file){
        ResultData msg = new ResultData(false);
        if (file == null) {
            return new ResultData(false, ConstantInfo.HttpCode.HTTP_400.getDesc(), ConstantInfo.HttpCode.HTTP_400.getValue());
        }

        try {
            // 保存文件
            String path = saveFile(file);
            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }

            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }
            OrderDetail orderDetail = orderService.findByCompanyIdAndParentId(deviceSerive.getDeviceId(deviceId),MEDIA_CAPACITY);
            if(orderDetail == null)
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_600.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_600.getDesc());
                return msg;
            }
            //过期
            if(orderDetail.getOutDate().getTime() < (new Date()).getTime())
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_601.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_601.getDesc());
                return msg;
            }
            List<Image> imageList = mediaService.searchByPath(deviceId, path);
            // 返回值
            msg.setSuccess(true);
            if (imageList != null) {
                msg.setData(imageList);
            }
            msg.setCode(ConstantInfo.HttpCode.HTTP_200.getValue());
            msg.setMsg(ConstantInfo.HttpCode.HTTP_200.getDesc());
            return msg;
        }catch (Exception e) {
            return null;
        }
    }
    /**
     * base64解码，保存文件
     * @param file 文件base64码
     * @return
     */
    private String saveFileByBase64(String file) {
        // 目录是否存在
        if(!new File(PathUtils.getBasePath() + recogPath).exists()){
            new File(PathUtils.getBasePath() + recogPath).mkdirs();
        }

        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // 解密
            byte[] bytes = decoder.decodeBuffer(file);
            // 处理数据
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }

            String newFileName = RandomUtil.getGUID().replaceAll("-", "") + ".jpg";
            Path path = Paths.get(PathUtils.getBasePath() + recogPath + newFileName);
            Files.write(path, bytes);
            return path.toString();
        } catch (Exception e) {
            log.info("文件编码解析失败");
            return null;
        }
    }

    /**
     * 保存文件
     * @param file 文件流
     * @return
     * @throws IOException
     */
    private String saveFile(MultipartFile file) throws IOException {
        if(!new File(PathUtils.getBasePath() + recogPath).exists()){
            new File(PathUtils.getBasePath() + recogPath).mkdirs();
        }
        if (file.isEmpty()) {
            return null;
        }

        byte[] bytes = file.getBytes();
        //设置一个随机文件名称
        String originalFileName = file.getOriginalFilename();
        String suffix = null;
        if (!StringUtil.isEmpty(originalFileName) && originalFileName.contains(DOT)) {
            suffix = originalFileName.substring(originalFileName.lastIndexOf(DOT));
        }

        String newFileName = RandomUtil.getGUID().replaceAll("-", "") + suffix;
        Path path = Paths.get(PathUtils.getBasePath() + recogPath + newFileName);
        Files.write(path, bytes);
        return path.toString();
    }


    /**
     * 人脸识别
     * 用于演示版本，如果找不到企业ID，直接赋值为4
     * @param deviceId 设备蓝牙地址
     * @param file 文件流
     * @return
     */
    @PostMapping("face/query2/{deviceId}")
    public ResultData recogFace2(@PathVariable String deviceId, MultipartFile file) {
        ResultData msg = new ResultData(false);
        if (file == null) {
            return new ResultData(false, ConstantInfo.HttpCode.HTTP_400.getDesc(), ConstantInfo.HttpCode.HTTP_400.getValue());
        }

        try {
            // 保存文件
            String path = saveFile(file);
            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }

            Integer companyId = deviceSerive.getDeviceId(deviceId);
            if (companyId == null) {
                companyId = 4 ;
            }
            OrderDetail orderDetail = orderService.findByCompanyIdAndParentId(companyId,PERSON_CAPACITY);
            if(orderDetail == null)
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_600.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_600.getDesc());
                return msg;
            }
            //过期
            if(orderDetail.getOutDate().getTime() < (new Date()).getTime())
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_601.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_601.getDesc());
                return msg;
            }
            // 识别文件
            List<PersonsVo> personsVoList = personsService.recogFace(deviceId, path);
            // 返回值
            msg.setSuccess(true);
            if (personsVoList != null) {
                msg.setData(personsVoList);
            }
            msg.setCode(ConstantInfo.HttpCode.HTTP_200.getValue());
            msg.setMsg(ConstantInfo.HttpCode.HTTP_200.getDesc());
            return msg;
        } catch (IOException e) {
            log.error("文件保存失败");
        }

        msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
        msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
        return msg;
    }


    /**
     * 指纹搜索/图像识别
     * 用于演示版本，如果找不到企业ID，直接赋值为4
     * @param deviceId
     * @param file
     * @return
     */
    @PostMapping("/image/query2/{deviceId}")
    public Msg search2(@PathVariable String deviceId, MultipartFile file){
        ResultData msg = new ResultData(false);
        if (file == null) {
            return new ResultData(false, ConstantInfo.HttpCode.HTTP_400.getDesc(), ConstantInfo.HttpCode.HTTP_400.getValue());
        }

        try {
            // 保存文件
            String path = saveFile(file);
            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }

            if (StringUtil.isEmpty(path)) {
                msg.setCode(ConstantInfo.HttpCode.HTTP_400.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc());
                return msg;
            }
            Integer companyId = deviceSerive.getDeviceId(deviceId);
            if (companyId == null) {
                companyId = 4 ;
            }
            OrderDetail orderDetail = orderService.findByCompanyIdAndParentId(companyId,MEDIA_CAPACITY);
            if(orderDetail == null)
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_600.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_600.getDesc());
                return msg;
            }
            //过期
            if(orderDetail.getOutDate().getTime() < (new Date()).getTime())
            {
                msg.setCode(ConstantInfo.HttpCode.HTTP_601.getValue());
                msg.setMsg(ConstantInfo.HttpCode.HTTP_601.getDesc());
                return msg;
            }
            List<Image> imageList = mediaService.searchByPath(deviceId, path);
            // 返回值
            msg.setSuccess(true);
            if (imageList != null) {
                msg.setData(imageList);
            }
            msg.setCode(ConstantInfo.HttpCode.HTTP_200.getValue());
            msg.setMsg(ConstantInfo.HttpCode.HTTP_200.getDesc());
            return msg;
        }catch (Exception e) {
            return null;
        }
    }
}
